//package com.example.app.page;
//
//import android.app.Application;
//import android.os.Bundle;
//import android.util.Log;
//import android.view.LayoutInflater;
//import android.view.View;
//import android.view.ViewGroup;
//import android.widget.TextView;
//import androidx.annotation.NonNull;
//import androidx.annotation.Nullable;
//import androidx.fragment.app.Fragment;
//import androidx.recyclerview.widget.LinearLayoutManager;
//import androidx.recyclerview.widget.RecyclerView;
//import com.example.app.R;
//import com.example.app.adapter.BillAdapter;
//import com.example.app.api.UploadService;
//import com.example.app.config.RetrofitClient;
//import com.example.app.entity.Reservation;
//import com.example.app.event.RefreshBillEvent;
//import com.example.app.manager.TokenManager;
//import org.greenrobot.eventbus.EventBus;
//import org.greenrobot.eventbus.Subscribe;
//import org.greenrobot.eventbus.ThreadMode;
//
//import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//import java.util.Locale;
//
//import retrofit2.Call;
//import retrofit2.Callback;
//import retrofit2.Response;
//
//public class BillFragment extends Fragment {
//
//    private static final String TAG = "Bill";
//    private RecyclerView billRecyclerView;
//    private BillAdapter billAdapter;
//    private List<Reservation> reservationList;
//    private TextView totalAmount;
//
//    private TokenManager tokenManager;
//
//    private RetrofitClient retrofitClient;
//
//    @Nullable
//    @Override
//    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        View view = inflater.inflate(R.layout.bill, container, false);
//
//        retrofitClient = RetrofitClient.getInstance((Application) requireContext().getApplicationContext());
//        tokenManager = retrofitClient.getTokenManager();
//
//        // 初始化RecyclerView
//        billRecyclerView = view.findViewById(R.id.billRecyclerView);
//        billRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//
//        // 初始化账单列表
//        reservationList = new ArrayList<>();
//        billAdapter = new BillAdapter(getContext(), reservationList);
//        billRecyclerView.setAdapter(billAdapter);
//
//        // 初始化总计金额
//        totalAmount = view.findViewById(R.id.totalAmount);
//
//
//        // 加载账单数据
//        loadBillData();
//
//        return view;
//    }
//
//    @Override
//    public void onStart() {
//        super.onStart();
//        // 注册 EventBus
//        EventBus.getDefault().register(this);
//    }
//
//    @Override
//    public void onStop() {
//        // 取消注册 EventBus
//        EventBus.getDefault().unregister(this);
//        super.onStop();
//    }
//
//    // 处理刷新事件
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onRefreshBillEvent(RefreshBillEvent event) {
//        Log.d(TAG, "接收到刷新账单事件");
//        loadBillData(); // 调用加载数据的方法
//    }
//
//    private void loadBillData() {
//        Log.e(TAG, "Token: " + tokenManager.getToken());
//        if (tokenManager.getToken() == null) {
//            Log.e(TAG, "请先登录！");
//            return;
//        }
//
//        // 获取用户服务接口实例（带Token）
//        UploadService uploadService = retrofitClient.getAuthService(UploadService.class);
//        Call<List<Reservation>> call = uploadService.getAllReservation(tokenManager.getUserId());
//
//        call.enqueue(new Callback<List<Reservation>>() {
//            @Override
//            public void onResponse(Call<List<Reservation>> call, Response<List<Reservation>> response) {
//                if (response.isSuccessful() && response.body() != null) {
//                    Log.e(TAG, "成功获取" + response.body().size() + "条预订数据");
//
//                    reservationList.clear();
//
//                    for (Reservation reservation : response.body()) {
//                        String formattedStartTime = formatDateTime(reservation.getStart_time());
//                        String formattedEndTime = formatDateTime(reservation.getEnd_time());
//
//                        reservation.setStart_time(formattedStartTime);
//                        reservation.setEnd_time(formattedEndTime);
//
//                        reservationList.add(reservation);
//                    }
//
//                    billAdapter.notifyDataSetChanged();
//                    calculateTotalAmount();
//                } else {
//                    Log.e(TAG, "请求失败: HTTP " + response.code());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<List<Reservation>> call, Throwable t) {
//                Log.e(TAG, "网络错误: " + t.getMessage());
//            }
//        });
//    }
//
//    private String formatDateTime(String iso8601DateTime) {
//        if (iso8601DateTime == null || iso8601DateTime.isEmpty()) {
//            return "";
//        }
//
//        try {
//            // 解析 ISO 8601 格式的时间
//            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
//            Date date = inputFormat.parse(iso8601DateTime);
//
//            // 格式化为 "yyyy-MM-dd HH:mm:ss"
//            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//            return outputFormat.format(date);
//        } catch (ParseException e) {
//            Log.e(TAG, "时间格式转换失败: " + e.getMessage());
//
//            // 尝试处理可能包含时区的情况（如 2025-05-11T10:56:32Z）
//            try {
//                SimpleDateFormat inputFormatWithTimeZone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.getDefault());
//                Date date = inputFormatWithTimeZone.parse(iso8601DateTime);
//                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//                return outputFormat.format(date);
//            } catch (ParseException ex) {
//                Log.e(TAG, "第二次尝试解析失败: " + ex.getMessage());
//                return iso8601DateTime;
//            }
//        }
//    }
//
//    private void calculateTotalAmount() {
//        double total = 0.0;
//        for (Reservation reservation : reservationList) {
//            String priceStr = reservation.getPrice();
//            if (priceStr != null &&!priceStr.isEmpty()) {
//                try {
//                    total += Double.parseDouble(priceStr);
//                } catch (NumberFormatException e) {
//                    Log.e(TAG, "价格格式错误: " + priceStr, e);
//                }
//            }
//        }
//        totalAmount.setText("¥" + String.format("%.2f", total));
//    }
//}
//
package com.example.app.page;

import android.app.Application;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.app.R;
import com.example.app.adapter.BillAdapter;
import com.example.app.api.UploadService;
import com.example.app.config.RetrofitClient;
import com.example.app.entity.EndOrderRequest;
import com.example.app.entity.Reservation;
import com.example.app.event.RefreshBillEvent;
import com.example.app.manager.TokenManager;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class BillFragment extends Fragment implements BillAdapter.OnItemClickListener {

    private static final String TAG = "Bill";
    private RecyclerView billRecyclerView;
    private BillAdapter billAdapter;
    private List<Reservation> reservationList;
    private TextView totalAmount;

    private TokenManager tokenManager;
    private RetrofitClient retrofitClient;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.bill, container, false);

        retrofitClient = RetrofitClient.getInstance((Application) requireContext().getApplicationContext());
        tokenManager = retrofitClient.getTokenManager();

        // 初始化RecyclerView
        billRecyclerView = view.findViewById(R.id.billRecyclerView);
        billRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 初始化账单列表
        reservationList = new ArrayList<>();
        billAdapter = new BillAdapter(getContext(), reservationList);

        // 设置点击监听器（关键修改点）
        billAdapter.setOnItemClickListener(this);

        billRecyclerView.setAdapter(billAdapter);

        // 初始化总计金额
        totalAmount = view.findViewById(R.id.totalAmount);

        // 加载账单数据
        loadBillData();

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        // 注册 EventBus
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        // 取消注册 EventBus
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    // 处理刷新事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshBillEvent(RefreshBillEvent event) {
        Log.d(TAG, "接收到刷新账单事件");
        loadBillData();
    }

    private void loadBillData() {
        Log.e(TAG, "Token: " + tokenManager.getToken());
        if (tokenManager.getToken() == null) {
            Log.e(TAG, "请先登录！");
            return;
        }

        // 获取用户服务接口实例（带Token）
        UploadService uploadService = retrofitClient.getAuthService(UploadService.class);
        Call<List<Reservation>> call = uploadService.getAllReservation(tokenManager.getUserId());

        call.enqueue(new Callback<List<Reservation>>() {
            @Override
            public void onResponse(Call<List<Reservation>> call, Response<List<Reservation>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Log.e(TAG, "成功获取" + response.body().size() + "条预订数据");

                    reservationList.clear();

                    for (Reservation reservation : response.body()) {
                        String formattedStartTime = formatDateTime(reservation.getStart_time());
                        String formattedEndTime = formatDateTime(reservation.getEnd_time());

                        reservation.setStart_time(formattedStartTime);
                        reservation.setEnd_time(formattedEndTime);

                        reservationList.add(reservation);
                    }

                    billAdapter.notifyDataSetChanged();
                    calculateTotalAmount();
                } else {
                    Log.e(TAG, "请求失败: HTTP " + response.code());
                }
            }

            @Override
            public void onFailure(Call<List<Reservation>> call, Throwable t) {
                Log.e(TAG, "网络错误: " + t.getMessage());
            }
        });
    }

    private String formatDateTime(String iso8601DateTime) {
        if (iso8601DateTime == null || iso8601DateTime.isEmpty()) {
            return "";
        }

        try {
            // 解析 ISO 8601 格式的时间
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
            Date date = inputFormat.parse(iso8601DateTime);

            // 格式化为 "yyyy-MM-dd HH:mm:ss"
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            return outputFormat.format(date);
        } catch (ParseException e) {
            Log.e(TAG, "时间格式转换失败: " + e.getMessage());

            // 尝试处理可能包含时区的情况（如 2025-05-11T10:56:32Z）
            try {
                SimpleDateFormat inputFormatWithTimeZone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.getDefault());
                Date date = inputFormatWithTimeZone.parse(iso8601DateTime);
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                return outputFormat.format(date);
            } catch (ParseException ex) {
                Log.e(TAG, "第二次尝试解析失败: " + ex.getMessage());
                return iso8601DateTime;
            }
        }
    }

    private void calculateTotalAmount() {
        double total = 0.0;
        for (Reservation reservation : reservationList) {
            String priceStr = reservation.getPrice();
            if (priceStr != null && !priceStr.isEmpty()) {
                try {
                    total += Double.parseDouble(priceStr);
                } catch (NumberFormatException e) {
                    Log.e(TAG, "价格格式错误: " + priceStr, e);
                }
            }
        }
        totalAmount.setText("¥" + String.format("%.2f", total));
    }

    @Override
    public void onEndOrderClick(int position) {
        Reservation reservation = reservationList.get(position);
        String orderId = reservation.getId();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault());
        String endTimeStr = sdf.format(new Date());

        Log.d(TAG, "订单ID: " + orderId);
        Log.d(TAG, "当前时间: " + endTimeStr);

        EndOrderRequest request = new EndOrderRequest(orderId, endTimeStr);

        // 获取用户服务接口实例（带Token）
        UploadService uploadService = retrofitClient.getAuthService(UploadService.class);
        Call<Void> call = uploadService.endOrder(request);

        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "订单结束成功，ID: " + orderId);
                    Toast.makeText(getContext(), "订单已结束", Toast.LENGTH_SHORT).show();

                    // 刷新账单数据
                    loadBillData();
                } else {
                    Log.e(TAG, "订单结束失败: HTTP " + response.code());
                    Toast.makeText(getContext(), "订单结束失败，请重试", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e(TAG, "网络错误: " + t.getMessage());
                Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
            }
        });

    }
}